package com.baomidou.springboot.helper;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;

/**
 * Created by zcy on 2017/7/13.s
 */
public class SeleniumTest {
    static {
        System.setProperty("webdriver.chrome.driver", "/Users/zcy/Downloads/chromedriver-2");
    }

    public static ChromeDriver driver = new ChromeDriver();

    public static void login() {

    }
    public static String  get(String url) throws Exception {
        if(driver==null)driver =new ChromeDriver();
        driver.get(url);
        String descHtml = getAjaxDesc();
        if (descHtml == null) {
            throw new Exception(String.format("请求阿里详情页加载中：%s", url));
        }
        String html = driver.getPageSource();
        return html;
    }
    public static void main(String[] args) throws Exception {
        String url = "https://detail.1688.com/offer/548705596794.html";
        //WebDriver driver = new ChromeDriverService("http://localhost:9515", DesiredCapabilities.chrome());
        driver.get(url);
        String descHtml = getAjaxDesc();
        if (descHtml == null) {
            throw new Exception(String.format("请求阿里详情页加载中：%s", url));
        }
        String html = driver.getPageSource();
        System.out.println(html);
        driver.quit();
    }

    public static String getAjaxDesc() throws InterruptedException {
        String descHtml = null;

        // 定义csdn底部 公司简介 这个元素
        WebElement element = driver.findElement(By.xpath("//*/div[@id='site_footer-box']"));
        //创建一个javascript 执行实例
        JavascriptExecutor je = (JavascriptExecutor) driver;
        //执行js语句，拖拽浏览器滚动条，直到该元素到底部，马上就不可以见
        je.executeScript("arguments[0].scrollIntoView(true);", element);

        WebElement searchBox = driver.findElement(By.id("desc-lazyload-container"));
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        String text = searchBox.getText();
        if (!text.startsWith("加载中")) descHtml = "已经存在";
        return descHtml;
    }

}
